﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class Monster : SceneFightObject
{
    public Vector3 SpawnPoint { get; private set; }

    public int AttackdelayTime = 1000;//攻击间隔

    private MonsterHpUI hpUI;

    public int MaxHealth { private set; get; }

    public EnumMonster monsterType { get; set; }
    

    private void Start()
    {
        hpUI = GetComponentInChildren<MonsterHpUI>();
    }

    private void OnEnable()
    {
        Mgr.fightMgr.fightEvent.AddListener(FightEvent.RESPLAYERFIGHTRESULT, ResFightResult);
        Mgr.fightMgr.fightEvent.AddListener(FightEvent.RESMONSTERATTACKPLAYER, ResMonsterAttackPlayer);
    }

    private void OnDisable()
    {
        Mgr.fightMgr.fightEvent.RemoveListener(FightEvent.RESPLAYERFIGHTRESULT, ResFightResult);
        Mgr.fightMgr.fightEvent.RemoveListener(FightEvent.RESMONSTERATTACKPLAYER, ResMonsterAttackPlayer);
    }

    private void ResMonsterAttackPlayer(object data)
    {
        GetComponent<MonsterControl>().SetAnimator(EnumAnimatorType.attack);
    }

    private void ResFightResult(object data)
    {
        //玩家空放
        if (data == null)
            return;

        bool isAttack = false;
        AttackInfo Attackinfo = data as AttackInfo;
        foreach(int id in Attackinfo.AttackedIds)
        {
            if(id == MonsterId)
            {
                isAttack = true;
            }
        }
        if (!isAttack)
            return;//不是此怪物被攻击

        int damage = Attackinfo.Damage - info.Defense;
        if (damage > 0)
            info.Health -= damage;
        info.Health = Mathf.Max(0, info.Health);

        hpUI.SetSliderValue(info.Health, MaxHealth);
        
    }

    //怪物ID
    public int MonsterId
    {
        set;
        get;
    }

    //设置出生位置
    public void SpawnOn(Vector3 pos)
    {
        SpawnPoint = transform.position = pos;
        
    }

    //设置怪物属性
    public void SetMonsterInfo(PlayerInfo info)
    {
        this.info = info;
        MaxHealth = info.Health;
    }

    private float time = 0;
    public override void Recycle()
    {
        if (Time.time - time > 1f)
        {
            time = Time.time;
            if(gameObject.activeSelf)
                StartCoroutine("ClearGameObj");
        }
    }

    IEnumerator ClearGameObj()
    {
        yield return new WaitForSeconds(2f);
        StopCoroutine("ClearGameObj");
        gameObject.SetActive(false);
        Mgr.monsterMgr.MonsterDie(transform);
    }

    public override bool GameUpdate()
    {
        if(info.Health <= 0)
        {
            return false;
        }

        return true;
    }

}
